# 创建一个会话
import time

import requests
import hashlib  # 哈希


def make_md5(text):
    m = hashlib.md5()  # 创建一个md5加密工具
    m.update(str(text).encode(encoding='utf-8'))
    res = m.hexdigest()  # 生成加密后的内容
    return res


username = f'rr{int(time.time())}'
email = username + '@qq.com'

s = requests.session()

# 注册
mydata = {
    "username": username,
    "password": "py1234",
    "cpassword": "py1234",
    "checkcode": "1234",
    "email": email
}

# 通过会话，发送请求，返回响应的数据
res = s.post(url="http://114.132.200.42:3456/user/register", data=mydata)
print(res.status_code)  # 查看响应的http状态码
print(res.headers)  # 查看响应的头部信息
print(res.json(), "注册成功")  # 查看响应的文本信息  以字典的方式接收
# print(res.text)  # 查看响应的文本信息 以字符串的方式接收
get_username = mydata["username"]
print(get_username)


# 登录
url = "http://114.132.200.42:3456/user/login"
login_data = {
    "username": get_username,
    "password": make_md5('py1234'),
    "checkcode": "1234"
}
res1 = s.post(url=url, data=login_data)
print(res1.json(), "登录成功")
# print(res1.text)
# print(res1.status_code)
# print(res1.json()["userId"])
# print(res1.json()["userToken"])

result = res1.json()
# print(result["userId"])
# print(result["userToken"])
get_userid = result["userId"]
get_userToken = result["userToken"]


# 创建任务
createUrl = "http://114.132.200.42:3456/task/info"
create_task = {"title": "1233434"}
# 头部信息 同意以字典的形式 存储
hd = {"userId": get_userid, "userToken": get_userToken}
res2 = s.post(url=createUrl, data=create_task, headers=hd)  # headers参数表示头部信息
print(res2.json(), "创建任务")
result1 = res2.json()

get_taskid = result1['taskid']
# print(get_taskid)

# 以json的形式发送请求参数 需要将参数名data改为json
# get请求无法使用json形式发送请求
# res5 = s.post(url=createUrl, json=create_task, headers=hd)
# print(res5.json())


# 查询任务  get请求
query_Url = "http://114.132.200.42:3456/task/info"
query_data = {"status": 0}
query = s.get(url=query_Url, params=query_data, headers=hd)
print(query.json(), "查询任务成功")

# 完成/取消任务
complete_url = "http://114.132.200.42:3456/task/info"
complete_data = {"task_id": get_taskid}
complete = s.put(url=complete_url, data=complete_data, headers=hd)
print(complete.json(), "完成任务")

# 完成/取消任务
cancel_url = "http://114.132.200.42:3456/task/info"
cancel_data = {"task_id": get_taskid}
cancel = s.put(url=cancel_url, data=cancel_data, headers=hd)
print(cancel.json(), "取消完成任务")

# 删除任务
delete_url = "http://114.132.200.42:3456/task/info"
delete_data = {"task_id": get_taskid}
delete = s.delete(url=delete_url, data=delete_data, headers=hd)
print(delete.json(), "删除成功")

# 文件上传
img_url = "http://114.132.200.42:3456/user/uploal_action"
# ('参数名',('文件名',open('文件路径','rb')))
my_img = [
    ('pic', ('pdx.jpg', open('pdx.png', 'rb')))
]
img = s.post(url=img_url, headers=hd, files=my_img)  # 关于文件上传的接口 files 表示
print(img.json(), "头像上传成功")
